package system_modules

import (
	"fmt"
	"gitee.com/theegg/go-brick/app/model"
	"gitee.com/theegg/go-brick/app/model/system/system_images"
	"gitee.com/theegg/go-brick/app/service/app"
	"gitee.com/theegg/go-brick/app/service/help/cslice"
	"strings"
)

// 查询参数
type QueryParams struct {
	PageSize  string `form:"page_size" binding:"gte=0,lte=100" label:"每页数量"`
	PageIndex string `form:"page_index" binding:"gte=0,lte=99999" label:"当前页数"`
}

// add 参数
type AddParams struct {
	Sign       string `form:"sign" binding:"required,min=2,max=32" label:"标识"`
	Title      string `form:"title" binding:"required,min=2,max=32" label:"标题"`
	Mark       string `form:"mark" binding:"" label:"描述"`
	ModuleType int    `form:"module_type" binding:"required,oneof=1 2" label:"模块类型"`
	ImageList  string `form:"image_list" label:"图片列表"`
	LinkList   string `form:"link_list" binding:"" label:"链接列表"`
	NodeList   string `form:"node_list" binding:"" label:"节点列表"`
}

// 模块类型
var ConfigureType = []map[string]interface{}{
	{
		"type":  1,
		"title": "图片类型",
		"fields": []map[string]string{
			{
				"image_list":     "",
				"link_list":      "",
				"link_type_list": "",
			},
		},
	},
	{
		"type":  2,
		"title": "文章类型",
	},
}

// 分页获取所有数据
// @param params map 参数
// @return interface{}, error
func GetDataList(params map[string]interface{}) ([]*SystemModules, error) {

	queryParams, errBuild := model.BuildAdminQueryParam(params)
	if errBuild != nil {
		return nil, app.NewError(errBuild)
	}

	query := app.Db().Desc("id").Limit(queryParams.Limit, queryParams.Offset)

	data := make([]*SystemModules, 0)
	// 求总条数
	err := query.Find(&data)
	if err != nil {
		return nil, app.NewError(err)
	}

	return data, nil
}

// 获取数据 通过ID
func GetItemById(id int64) (*SystemModules, error) {
	item := new(SystemModules)

	has, err := app.Db().ID(id).Get(item)

	if err != nil {
		return nil, err
	} else {
		if !has {
			return item, nil
		}
	}

	return item, nil
}

// 获取数据 通过 sign
func GetItemBySign(sign string) (*SystemModules, error) {
	item := new(SystemModules)

	has, err := app.Db().Where("sign = ?", sign).Get(item)

	if err != nil {
		return nil, err
	} else {
		if !has {
			return item, nil
		}
	}

	return item, nil
}

// 添加 / 更新 管理
// 不用反射合并结构体
func (pc *SystemModules) AddOrUpdateSystemModule(params AddParams) (*SystemModules, error) {

	var affected int64
	var errInsert error

	// 检测sign 唯一性
	if pc.Id == 0 {
		if IsFiledValueUnique("sign", params.Sign) {
			return nil, app.NewError("对不起, sign值已经存在")
		}
	} else {
		if pc.Sign != params.Sign {
			if IsFiledValueUniqueExcept("sign", params.Sign, pc.Sign) {
				return nil, app.NewError("对不起, sign值已经存在")
			}
		}
	}

	// 图片处理
	imageChangeList := map[string][]string{
		"add": make([]string, 0),
		"del": make([]string, 0),
	}

	// 1. 图片集合拆解
	imageList := make([]string, 0)
	for _, v := range strings.Split(params.ImageList, ",") {
		if v != "" {
			imageList = append(imageList, v)
		}
	}

	if pc.Id > 0 {
		if pc.ImageList != "" {
			imageOldList := strings.Split(pc.ImageList, ",")
			if len(imageOldList) > 0 {
				imageChangeList["del"] = append(imageChangeList["del"], cslice.StringSliceMainDiff(imageOldList, imageList)...)
				imageChangeList["add"] = append(imageChangeList["add"], cslice.StringSliceMainDiff(imageList, imageOldList)...)
			}
		}
	} else {
		imageChangeList["add"] = imageList
	}

	pc.Sign = params.Sign
	pc.Title = params.Title
	pc.Mark = params.Mark
	pc.ModuleType = params.ModuleType

	if params.ModuleType == 1 {
		pc.ImageList = params.ImageList
		pc.LinkList = params.LinkList
	} else {
		pc.NodeList = params.NodeList
	}

	if pc != nil && pc.Id > 0 {
		// 更新数据
		affected, errInsert = app.Db().ID(pc.Id).Update(pc)

		if errInsert != nil {
			return nil, app.NewError(errInsert)
		}
	} else {
		pc.Status = true

		affected, errInsert = app.Db().Insert(pc)

		if errInsert != nil {
			return nil, app.NewError(errInsert)
		}

		if affected != 1 {
			return nil, app.NewError("新增菜单错误(0x001)")
		}
	}

	// 图片处理
	errImage := system_images.ProcessItemImage(pc.Id, imageChangeList)
	if errImage != nil {
		return pc, app.NewError(errImage)
	}

	return pc, nil
}

// 模块配置
func GetModuleConfig(moduleSign string) ([]map[string]string, error) {
	module, err := GetItemBySign(moduleSign)
	if err != nil {
		return nil, app.NewError(err)
	}

	config := make([]map[string]string, 0)
	if module.ModuleType == 1 && module.ImageList != "" {
		imageList := strings.Split(module.ImageList, ",")
		linkList := strings.Split(module.LinkList, ",")
		fmt.Println(imageList)

		for i, v := range imageList {
			tmp := make(map[string]string)
			tmp["image_url"] = app.GetImageStaticUrl(v)
			tmp["direct_path"] = linkList[i]
			config = append(config, tmp)
		}
	}

	return config, nil
}

/** =============================  辅助函数 ============================= */
// 检测字段唯一性
func IsFiledValueUnique(field string, value interface{}) bool {
	user := new(SystemModules)

	has, err := app.Db().Where(field+" = ?", value).Get(user)

	if err != nil {
		return false
	} else {
		if !has {
			return false
		}
	}

	return true
}

// 检测字段唯一性 排除指定
func IsFiledValueUniqueExcept(field string, value interface{}, except interface{}) bool {
	model := new(SystemModules)

	has, err := app.Db().Where(field+" = ?", value).Get(model)

	if err != nil {
		return false
	} else {
		if !has {
			return false
		}
	}

	// 排除指定值
	if model.Sign == except {
		return false
	}

	return true
}
